package com.qf.shiro;

import com.qf.pojo.DtsAd;
import com.qf.pojo.DtsAdmin;
import com.qf.pojo.DtsPermission;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class AdminAuthorizingRealm extends AuthorizingRealm {
    @Autowired
    DtsAdminService dtsAdminService;


    @Autowired
    DtsRoleService roleService;

    @Autowired
    DtsPermissionService permissionService;

    //提供授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取认证成功后的对象
        DtsAdmin admin = (DtsAdmin) principalCollection.getPrimaryPrincipal();
        //获取 该admin对应的角色id
        Integer[] roleIds = admin.getRoleIds();
        //根据角色id获取角色信息
        Set<String> roles = roleService.findRoleByIds(roleIds);
        //根据角色id获取权限信息
        Set<String> perms = permissionService.findRoleByIds(roleIds);


        SimpleAuthorizationInfo authenticationInfo = new SimpleAuthorizationInfo();
        authenticationInfo.setRoles(roles);
        authenticationInfo.setStringPermissions(perms);
        return authenticationInfo;
    }
    //提供认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户输入的账号和密码
        //获取用户名
        String username = (String) token.getPrincipal();
        //获取密码
        String password = new String((char[])token.getCredentials());
        //获取数据库的该用户信息
        DtsAdmin admin = dtsAdminService.findByUsername(username);

        //校验
        if (admin == null){
            throw new UnknownAccountException("未知的账户");
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (admin.getPassword() == null || ! passwordEncoder.matches(password,admin.getPassword())){
            throw new CredentialsException("密码错误");
        }
        //如果deleted为1 账户已经锁定
        if (admin.getDeleted()){
            throw new LockedAccountException("账户已经被锁定");
        }
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(admin,password,admin.getUsername());

        return authenticationInfo;
    }
}
